package pc

import (
	"fmt"
	"math/rand"
	"path"
	"strconv"
	"strings"
	"tcsc/controllers/mobile"
	"tcsc/models"
	"tcsc/sword"
	"time"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

// "sword"

type Search struct {
	BaseController
}

func (c *Search) Get() {
	shopWhere := ""
	if c.ShopId != "" {
		shopWhere = " a.gid = " + c.ShopId
	} else {
		shopWhere = " a.gid not in(select id from mt_shop where style=1)"
	}

	cid := c.GetString("cid")
	bid := c.GetString("bid")
	search := c.GetString("search")
	searchType := c.GetString("type")
	c.Data["cid"] = cid
	c.Data["bid"] = bid
	c.Data["search"] = search
	c.Data["searchType"] = searchType
	var w []string
	w = append(w, `a.status=1`)
	w = append(w, `a.censoring=1`)
	page, page2, num := models.Pagechange(c.GetString("page"), fmt.Sprint(models.Systems()["pnum"]))
	status := c.GetString("status")

	c.Data["status"] = status
	min := c.GetString("min")
	if min != "" {
		w = append(w, `a.price>=`+min)
	}
	max := c.GetString("max")
	if max != "" {
		w = append(w, `a.price<=`+max)
	}
	c.Data["min"] = min
	c.Data["max"] = max
	p, _ := c.GetInt("page")
	if p == 0 {
		p = 1
	}
	c.Data["pagep"] = p - 1
	c.Data["pagel"] = p + 1
	var ob string
	switch status {
	case "":
		ob = ` order by a.addtime desc `
	case "1":
		ob = ` order by a.sellnum desc `
	case "2":
		ob = ` order by a.addtime desc `
	case "3":
		ob = ` order by a.price `
	case "4":
		ob = ` order by a.price desc `
	}
	lt := ` limit ` + page + `,` + num
	var aids []string
	//是搜索的页面
	if searchType == "2" {
		limit := ` limit 20`
		page, page2, nums := models.Pagechange(c.GetString("page"), "20")
		if c.GetString("page") != "" {
			limit = ` limit ` + page + `, ` + nums
		}
		sql := `select a.name,a.id as gid,a.type,c.pathname from mt_shop a left join mt_resources c on a.logo=c.id where a.status=1 and a.style=1 and a.censoring=1`
		ob := ` group by a.name  order by a.recommend desc,a.sort desc,a.addtime desc`
		if search != "" {
			sql += ` and a.name like '%` + search + `%'` + ob + limit
		} else {
			sql += ob + limit
		}
		info := models.Query(sql)
		for _, v := range info {
			if v["gid"] != nil {
				gid := v["gid"].(string)
				v["num"] = models.Query(`select count(*) as num from mt_member_focus where gid=?`, gid)[0]["num"]
				t := strings.Trim(fmt.Sprint(v["type"]), ",")
				if t == "" {
					t = "''"
				}
				v["fw"] = models.Query(`select id,name from mt_column where id in (` + t + `)`)
				// sellnum := models.Query(`select count(*) as num from mt_order_car where status>1 and gid=?`, gid)[0]["num"]
				// if sellnum == nil {
				// 	v["sellnum"] = 0
				// } else {
				// 	v["sellnum"] = sellnum
				// }
				product := mobile.ProductList(`select a.id,b.pathname,a.sellnum,a.issellnum,a.isvip,a.minbuy,a.price from mt_product a left join mt_resources b on a.img=b.id where 
			a.censoring=1 and a.status=1 and a.gid=`+gid+` order by a.grecommend desc,a.gsort desc`, c.Uid)
				pnum := len(product)
				v["pnum"] = pnum
				if pnum >= 3 {
					v["product"] = product[0:3]
				} else {
					v["product"] = product
				}
			}
		}
		// sql2 := `select count(*) as totals from mt_shop where `
		c.Data["url"] = `/search_all?search=` + search + `&type=2` + `&`
		// c.Data["paginator"] = models.Page(sql2, page2, num)
		totals := string(len(info))
		total, _ := strconv.ParseInt(totals, 10, 64)
		num, _ := strconv.Atoi(nums)
		if total == 0 {
			c.Data["paginator"] = models.Paginator(1, num, int64(num))
		} else {
			c.Data["paginator"] = models.Paginator(page2, num, total)
		}
		c.Data["info"] = info
		c.TplName = "pc/search/shop.html"
	} else {

		if search != "" {
			//
			var w2 []string
			w2 = append(w2, `a.title like '%`+search+`%'`)
			w2 = append(w2, `a.keywords like '%`+search+`%'`)
			w2 = append(w2, `a.model like '%`+search+`%'`)
			// w2 = append(w2, `a.barcode like '%`+search+`%'`)
			w2s := strings.Join(w2, ` or `)
			if w2s != "" {
				w2s = `(` + w2s + `)`
				w = append(w, w2s)
			}
			w = append(w, shopWhere)
			//品牌
			brand := models.Query(`select a.*,b.pathname  
			from mt_brand a 
			left join mt_resources b on a.logo=b.id 
			where a.status=1 and a.censoring=1 and a.name like '%` + search + `%'`)
			var bids []string
			for _, v := range brand {
				bids = append(bids, v["id"].(string))
				if status == "" {
					ob = ` order by l.pid,a.cid desc,a.recommend desc,a.sort desc,a.addtime desc `
				}
			}
			bidss := strings.Join(bids, ",")
			if bidss != "" {
				w2 = append(w2, `a.bid in(`+bidss+`)`)
			}
			ws := strings.Join(w, ` and `)
			product := ProductSearch(`
			select a.*,b.pathname,c.name as gname  
			from mt_product a
			left join mt_resources b on a.img=b.id 
			left join (select * from mt_shop where status=1 and censoring=1 and style=1) c on a.gid=c.id 
			left join mt_column l on a.cid=l.id 
			where `+ws+ob+lt, c.Uid)
			sql2 := `select count(a.id) as totals from mt_product a where ` + ws
			c.Data["paginator"] = models.Page(sql2, page2, num)
			c.Data["brand"] = brand
			c.Data["product"] = product
			c.Data["title"] = "搜索结果"
			//品牌
		} else {
			c.Data["title"] = "产品列表"
			var column orm.Params
			var brand orm.Params
			if cid != "" {
				var cids []string
				cids = append(cids, cid)
				column = models.Query(`select a.* from mt_column a where a.id=` + cid)[0]
				columnson := models.Query(`select a.* from mt_column a where a.pid=` + cid)
				for _, v := range columnson {
					cids = append(cids, v["id"].(string))
					son := models.Query(`select a.* from mt_column a where a.pid=` + v["id"].(string))
					for _, s := range son {
						cids = append(cids, s["id"].(string))
					}
				}
				cidss := strings.Join(cids, ",")
				w = append(w, `a.cid in(`+cidss+`)`)
				c.Data["title"] = column["name"]
				if bid == "" {
					c.Data["brand"] = models.Query(`select a.*,b.pathname  
			from mt_brand a 
			left join mt_resources b on a.logo=b.id 
			where a.status=1 and a.censoring=1 and a.cid like '%,` + cid + `,%'`)
				}
				attrcolumn := models.Query(`select a.* from mt_product_attribute_column a where a.cid=` + cid)
				for _, v := range attrcolumn {
					aid := v["id"].(string)
					attr := models.Query(`select a.* from mt_product_attribute_column a where a.cid=` + aid)
					av := c.GetString("a" + aid)
					if av != "" {
						aids = append(aids, "a"+aid+"="+av)
						v["isselect"] = 1
						w = append(w, `a.attr like '%,`+av+`,%'`)
						for _, a := range attr {
							if a["id"].(string) == av {
								a["isthis"] = 1
							}
						}
					}
					v["attr"] = attr
				}
				c.Data["attrcolumn"] = attrcolumn
			}
			if bid != "" {
				brand = models.Query(`select a.*,b.pathname from mt_brand a left join mt_resources b on a.logo=b.id where a.id=` + bid)[0]
				w = append(w, `a.bid=`+bid)
				c.Data["title"] = brand["name"]
				switch status {
				case "":
					ob = ` order by l.pid`
				case "1":
					ob = ` order by a.sellnum desc `
				case "2":
					ob = ` order by a.addtime desc `
				case "3":
					ob = ` order by a.price `
				case "4":
					ob = ` order by a.price desc `
				}
			}
			if column != nil && brand != nil {
				c.Data["title"] = fmt.Sprintf(`%v-%v`, column["name"], brand["name"])
			}
			w = append(w, shopWhere)
			ws := strings.Join(w, ` and `)
			sql := `select a.*,b.pathname,c.name as gname 
			from mt_product a 
			left join mt_resources b on a.img=b.id 
			left join (select * from mt_shop where status=1 and censoring=1 and style=1) c on a.gid=c.id 
			left join mt_column l on a.cid=l.id 
			where  ` + ws + ob + lt
			product := ProductSearch(sql, c.Uid)
			c.Data["product"] = product
			sql2 := `select count(a.id) as totals from mt_product a where ` + ws
			c.Data["paginator"] = models.Page(sql2, page2, num)
		}
		aidss := strings.Join(aids, "&")
		if aidss != "" {
			aidss = "&" + aidss
		}
		c.Data["url"] = `/search_all?search=` + search + `&bid=` + bid + `&cid=` + cid + `&status=` + status + aidss + `&`
		c.Data["statusurl"] = `/search_all?search=` + search + `&bid=` + bid + `&cid=` + cid + `&page=&min=` + min + `&max=` + max + aidss + `&`
		c.Data["priceurl"] = `/search_all?search=` + search + `&bid=` + bid + `&cid=` + cid + aidss + `&`
		c.Data["attrurl"] = `/search_all?search=` + search + `&bid=` + bid + `&cid=` + cid + aidss + `&min=` + min + `&max=` + max + `&`
		c.Data["brandurl"] = `/search_all?search=` + search + `&cid=` + cid + aidss + `&min=` + min + `&max=` + max + `&`
		c.Data["recommend"] = ProductSearch(`select a.*,b.pathname,c.name as gname 
			from mt_product a 
			left join mt_resources b on a.img=b.id 
			left join (select * from mt_shop where status=1 and censoring=1 and style=1) c on a.gid=c.id 
			where a.status=1 and a.censoring=1 and a.recommend=1 and `+shopWhere+` ORDER BY RAND() LIMIT 10`, c.Uid)
		c.TplName = "pc/search/index.html"
	}
}

type ProductContent struct {
	BaseController
}

func (c *ProductContent) Get() {
	id := c.GetString("id")
	now := sword.Gettimes("")
	if id == "" {
		c.StopRun()
		return
	}
	page, page2, num := models.Pagechange(c.GetString("page"), "20")
	var w []string
	w = append(w, `a.sid=0`)
	w = append(w, `a.status=1`)
	w = append(w, `a.censoring=1`)
	ws := strings.Join(w, ` and `)
	ob := ` order by a.addtime desc `
	lt := ` limit ` + page + `,` + num
	sql := `select a.id,a.score,a.img,a.addtime,a.content,c.pathname,b.monicker,d.num 
			from mt_product_evaluation a 
			left join mt_member b on a.uid=b.id 
			left join mt_resources c on b.avatar=c.id 
			join (select * from mt_order_car where pid=` + id + `) d on a.cid=d.id 
			where ` + ws + ob + lt
	evaluate := models.Query(sql)
	for _, v := range evaluate {
		if img := fmt.Sprint(v["img"]); img != "" && img != "<nil>" {
			v["imgs"] = models.Query(`select pathname from mt_resources where id in(` + img + `)`)
		}

		monicker := fmt.Sprint(v["monicker"])
		monickers := strings.Split(monicker, "")
		v["monicker"] = monickers[0] + `****` + monickers[len(monickers)-1]
	}
	sql2 := `select count(a.id) as totals 
				from mt_product_evaluation a 
				join (select * from mt_order_car where pid=` + id + `) d on a.cid=d.id 
				where ` + ws
	paginator := models.Page(sql2, page2, num)
	if c.IsAjax() {
		var js = make(map[string]interface{})
		js["evaluate"] = evaluate
		js["paginator"] = paginator
		c.Data["json"] = js
		c.ServeJSON()
	} else {
		c.Data["paginator"] = paginator
		c.Data["evaluate"] = evaluate
		product := models.Query(`select a.issingle,a.id,a.barcode,a.title,a.price,a.minbuy,a.gid,a.image,a.cid,a.content,a.click,a.length,a.description,
				d.style, a.attr,a.material,a.width,a.height,a.weight,a.number,a.spec,a.isvip,a.inventory,a.sellnum,a.issellnum,a.model,a.size,
				b.pathname,c.name as bname 
				from mt_product a 
				left join mt_resources b on a.img=b.id 
				left join mt_brand c on a.bid=c.id 
				left join mt_shop d on a.gid=d.id 
				where a.id=` + id + ` and a.censoring=1 and a.status=1`)
		if product == nil {
			if product2 := models.Query(`select cid from mt_product where id=` + id); product2 != nil {
				cid := product2[0]["cid"].(string)
				recommend := mobile.ProductList(`select a.price,a.id,b.pathname,a.title,a.isvip 
					from mt_product a 
					left join mt_resources b on a.img=b.id 
					where a.cid=`+cid+` and a.status=1 and a.censoring=1 and a.recommend=1 and a.id<>`+id+` 
					order by a.sort desc 
					limit 8`, c.Uid)
				if c.IsAjax() {
					var js = make(map[string]interface{})
					js["npr"] = recommend
					c.Data["json"] = js
					c.ServeJSON()
				} else {
					c.Data["recommend"] = recommend
					c.TplName = "pc/column/noproduct.html"
				}
				return
			} else {
				c.StopRun()
			}
		}
		cid := fmt.Sprint(product[0]["cid"])
		gid := fmt.Sprint(product[0]["gid"])
		style := fmt.Sprint(product[0]["style"])
		mobile.ProductClick(id, c.Uid)
		var img []string
		if pathname, ok := product[0]["pathname"].(string); ok {
			img = append(img, pathname)
		}
		if image := fmt.Sprint(product[0]["image"]); image != "" && image != "<nil>" {
			imgs := models.Query(`select pathname from mt_resources where id in(` + image + `)`)
			for _, i := range imgs {
				p := fmt.Sprint(i["pathname"])
				if c.ShopId != "" {
					pathname := strings.TrimLeft(p, "/")
					ext := path.Ext(pathname)
					source := strings.TrimRight(pathname, ext) + "-source" + ext
					isExists, _ := PathExists(source)
					if !isExists {
						source = pathname + "-source" + strings.ToLower(ext)
						isExists, _ = PathExists(source)
						if !isExists {
							source = pathname
						}
					}
					source = "/" + source
					img = append(img, source)
				} else {
					img = append(img, p)
				}
			}
		}
		product[0]["imgs"] = img
		if c.ShopId != "" {
			content := fmt.Sprint(product[0]["content"])
			if content != "" {
				imgs := sword.UeditorImg(content)
				for _, v := range imgs {
					pathname := strings.TrimLeft(v, "/")
					ext := path.Ext(pathname)
					source := strings.TrimRight(pathname, ext) + "-source" + ext
					isExists, _ := PathExists(source)
					if !isExists {
						source = pathname + "-source" + strings.ToLower(ext)
						isExists, _ := PathExists(source)
						if !isExists {
							source = pathname
						}
					}
					content = strings.Replace(content, pathname, source, -1)
				}
			}
			product[0]["content"] = content
		}
		price, _ := strconv.ParseFloat(fmt.Sprint(product[0]["price"]), 64)
		number, _ := strconv.ParseFloat(fmt.Sprint(product[0]["number"]), 64)

		if gid == "<nil>" {
			gid = "0"
		}

		pricem := price * number
		product[0]["price"] = fmt.Sprintf(`%.2f`, price)
		product[0]["pricem"] = fmt.Sprintf(`%.2f`, pricem)
		if sales := models.Query(`select price from mt_active_sales where pid=` + id + ` and status=1 and end=0 and 
			starttime<='` + now + `' and endtime>='` + now + `'`); sales != nil {
			price := fmt.Sprint(sales[0]["price"])
			product[0]["price"] = price
			pricem := sword.Mult(price, fmt.Sprint(number))
			product[0]["pricem"] = pricem
		}

		if c.Uid != "" {
			if fmt.Sprint(product[0]["isvip"]) == "1" {
				nowgid := gid
				if style == "0" {
					nowgid = "0"
				}
				mem := models.Query(`
						select b.fold 
						from mt_member_vip_order a 
						join (select * from mt_member_vip where gid=? and status=1) b on a.vid=b.id 
						where a.uid=?`, nowgid, c.Uid)

				if mem != nil {
					if fold := fmt.Sprint(mem[0]["fold"]); fold != "" && fold != "<nil>" {
						vprice := sword.Divi(sword.Mult(fmt.Sprint(product[0]["price"]), fold), "100")
						product[0]["vprice"] = vprice
						number := fmt.Sprint(product[0]["number"])
						product[0]["vpricem"] = sword.Mult(vprice, number)
					}
				}
			}
		}

		//
		//销量
		if fmt.Sprint(product[0]["issellnum"]) == "1" {
			sellnum := models.Query(`select sum(a.num) as num from mt_order_car a where a.status>1 and a.pid=` + id)[0]["num"]
			if sellnums, ok := sellnum.(string); ok {
				product[0]["sellnum"] = sellnums
			} else {
				product[0]["sellnum"] = "0"
			}
		}
		attr := fmt.Sprint(product[0]["attr"])
		attr = strings.Trim(attr, ",")
		if attr == "" || attr == "<nil>" {
			attr = "''"
		}
		product[0]["attrs"] = models.Query(`select a.name as value,b.name from mt_product_attribute a left join mt_product_attribute_column
				 b on a.cid=b.id where a.id in(` + attr + `) order by b.sort desc`)
		product[0]["parameter"] = models.Query(`select a.key,a.value from mt_product_parameter a where a.pid=` + id + ` and a.status=1 order by a.sort desc`)
		var gidcou = "0"
		var iscollect int
		if c.Uid != "" {
			if isc := models.Query(`select id from mt_member_focus where uid=` + c.Uid + ` and gid=` + gidcou); isc != nil {
				iscollect = 1
			}
		}
		product[0]["iscollect"] = iscollect
		var ptype string
		// a.style=1 and
		beego.Debug(gid)
		if shop := models.Query(`select a.id,a.tel,a.type,a.name,b.pathname,c.name as shen,d.name as shi,e.pathname as bpath 
			from mt_shop a 
			left join mt_resources b on a.logo=b.id 
			left join mt_area c on a.province=c.code 
			left join mt_area d on a.city=d.code 
			left join mt_resources e on a.webimg=e.id 
			where a.id=` + gid); shop != nil {

			c.Data["shop"] = shop[0]
			gidcou = gid
			ptype = shop[0]["type"].(string)
			ptype = ptype[1 : len(shop[0]["type"].(string))-1]
		}
		c.Data["recommend"] = mobile.ProductList(`select a.price,a.id,b.pathname,a.title,a.isvip from mt_product a left join mt_resources b on 
				a.img=b.id where a.cid=`+cid+` and a.status=1 and a.censoring=1 and a.recommend=1 and a.id<>`+id+` order by a.sort desc limit 5`, c.Uid)
		c.Data["grecommend"] = mobile.ProductList(`select a.price,a.id,b.pathname,a.title,a.isvip from mt_product a left join mt_resources b on 
				a.img=b.id where a.gid=`+gid+` and a.status=1 and a.censoring=1 and a.grecommend=1 and a.id<>`+id+` order by a.gsort desc limit 5`, c.Uid)
		if gbuy := models.Query(`select id,price,endtime,num,min from mt_active_gbuy where end=0 and pid=` + id + ` and status=1 and starttime<='` + now + `' and endtime>'` + now + `' 
				order by addtime desc`); gbuy != nil {
			for _, v := range gbuy {
				endtime := fmt.Sprint(v["endtime"])
				nt := time.Now().Local()
				loc, _ := time.LoadLocation("Local")
				et, _ := time.ParseInLocation(Tparse, endtime, loc)
				res := et.Sub(nt)
				h := int(res.Hours())
				m := int(res.Minutes())
				s := int(res.Seconds())
				hi := h
				mi := m % 60
				si := s % 60
				var sysj []string
				if hi < 10 {
					sysj = append(sysj, fmt.Sprintf("0%v", hi))
				} else if hi >= 10 {
					sysj = append(sysj, fmt.Sprintf("%v", hi))
				}
				if mi < 10 {
					sysj = append(sysj, fmt.Sprintf("0%v", mi))
				} else if mi >= 10 {
					sysj = append(sysj, fmt.Sprintf("%v", mi))
				}
				if si < 10 {
					sysj = append(sysj, fmt.Sprintf("0%v", si))
				} else if si >= 10 {
					sysj = append(sysj, fmt.Sprintf("%v", si))
				}
				v["sysj"] = strings.Join(sysj, ":")
				jnum := models.Query(`select sum(b.num) as jnum from mt_order a join mt_order_car b on a.carid=b.id where a.type=1 and 
					a.status>=2 and a.agid=` + v["id"].(string))[0]["jnum"]
				if jnum == nil {
					v["jnum"] = "0"
				} else {
					v["jnum"] = jnum
				}
				v["gprice"] = sword.Mult(fmt.Sprint(v["price"]), fmt.Sprint(product[0]["number"]))
			}
			c.Data["gbuy"] = gbuy[0]
		}

		coupon := models.Query(`select id,name,full,offer,effective,date_format(starttime,'%Y-%m-%d') as starttime,date_format(endtime,'%Y-%m-%d') 
				as endtime from mt_coupon where status=1 and starttime<='` + now + `' and endtime>'` + now + `' and gid=` + gidcou)
		for _, v := range coupon {
			v["isget"] = 0
			if c.Uid != "" {
				if is := models.Query(`select id from mt_member_coupon where uid=` + c.Uid + ` and yid=` + v["id"].(string) + ` and status=1`); is != nil {
					v["isget"] = 1
				}
			}
		}
		c.Data["coupon"] = coupon
		score := models.Query(`select avg(score) as avgscore,avg(logisticsscore) as avglogisticsscore 
			from mt_shop_evaluation where gid=` + gidcou)
		for _, v := range score {
			if avgscore, ok := v["avgscore"].(string); ok {
				avgscoref, _ := strconv.ParseFloat(avgscore, 64)
				v["avgscore"] = fmt.Sprintf(`%.1f`, avgscoref)
			} else {
				v["avgscore"] = 5
			}
			if logisticsscore, ok := v["logisticsscore"].(string); ok {
				logisticsscoref, _ := strconv.ParseFloat(logisticsscore, 64)
				v["logisticsscore"] = fmt.Sprintf(`%.1f`, logisticsscoref)
			} else {
				v["logisticsscore"] = 5
			}
		}
		c.Data["score"] = score[0]
		c.Data["info"] = product[0]
		c.Data["gid"] = gidcou
		if ptype != "" {
			c.Data["column"] = models.Query(`select id,name from mt_column where id in (` + ptype + `) and pid=0 and type='p' and status=1`)
		} else {
			c.Data["column"] = models.Query(`select id,name from mt_column where pid=0 and type='p' and status=1`)
		}

		c.TplName = "pc/product/index.html"
	}
}

// func (c *ProductContent) Post() {
// 	gid := c.GetString("gid")
// }

type ProductGetcoupon struct {
	BaseController
}

func (c *ProductGetcoupon) Get() {
	defer c.ServeJSON()
	yid := c.GetString("yid")
	if yid == "" {
		c.Data["json"] = 0
		return
	}
	if c.Uid == "" {
		c.Data["json"] = 2
		return
	}
	if is := models.Query(`select id from mt_member_coupon where status=1 and uid=` + c.Uid + ` and yid=` + yid); is != nil {
		c.Data["json"] = 3
		return
	}
	if err := models.Exec(`insert into mt_member_coupon (uid,yid,addtime,status) values (` + c.Uid + `,` + yid + `,'` + sword.Gettimes("") + `',1)`); err != nil {
		beego.Debug(err)
		c.Data["json"] = 0
	} else {
		c.Data["json"] = 1
	}

}

type ColumnProductCollect struct {
	BaseController
}

func (c *ColumnProductCollect) Post() {
	defer c.ServeJSON()
	if c.Uid == "" {
		c.Data["json"] = 2
	} else {
		id := c.GetString("id")
		if id != "" {
			if is := models.Query(`select id from mt_member_collection where uid=` + c.Uid + ` and pid=` + id); is != nil {
				if err := models.Exec(`delete from mt_member_collection where id=` + is[0]["id"].(string)); err != nil {
					beego.Debug(err)
					c.Data["json"] = 0
				} else {
					c.Data["json"] = 1
				}
			} else {
				if err := models.Exec(`insert into mt_member_collection (uid,pid,addtime) values (` + c.Uid + `,` + id + `,'` + sword.Gettimes("") + `')`); err != nil {
					beego.Debug(err)
					c.Data["json"] = 0
				} else {
					c.Data["json"] = 1
				}
			}
		}
	}
}

type ColumnProductLost struct {
	BaseController
}

func (c *ColumnProductLost) Post() {
	defer c.ServeJSON()
	if c.Uid == "" {
		c.Data["json"] = 2
	} else {
		if is := models.Query(`select id from mt_product_lost where pid=` + c.GetString("pid") + ` and uid=` + c.Uid); is != nil {
			c.Data["json"] = 3
		} else {
			if err := models.Exec(fmt.Sprintf(`insert into mt_product_lost (uid,pid,num,addtime) values ('%v','%v','%v','%v')`, c.Uid, c.GetString("pid"),
				c.GetString("num"), sword.Gettimes(""))); err != nil {
				beego.Debug(err)
				c.Data["json"] = 0
			} else {
				c.Data["json"] = 1
			}
		}
	}
}

type ColumnList struct {
	BaseController
}

func (c *ColumnList) Get() {
	cid := c.GetString("id")
	if cid == "" {
		c.StopRun()
	}
	column := models.Query(`select a.id,a.level,a.pid,a.name,b.pathname from mt_column a left join mt_resources b on a.img=b.id where a.id=` + cid)[0]
	level := fmt.Sprint(column["level"])
	var cids []string
	cids = append(cids, cid)
	var pcid string
	if level == "2" {
		columns := models.Query(`select id from mt_column where pid=` + cid + ` and gid=0 and status=1`)
		for _, v := range columns {
			cids = append(cids, v["id"].(string))
		}
		pcid = cid
	} else {
		pcid = fmt.Sprint(column["pid"])
	}
	urls := `/mobile/column/list?`
	attribute_column := models.Query(`select id,name from mt_product_attribute_column where status=1 and cid=` + pcid + ` order by sort desc`)
	var w []string
	for _, v := range attribute_column {
		aid := v["id"].(string)
		v["attribute"] = models.Query(`select id,name from mt_product_attribute where cid=` + aid)
		paid := c.GetString(aid)
		if paid != "" {
			w = append(w, `a.attr like '%`+paid+`%'`)
			urls += aid + `=` + paid + `&`
			v["value"] = paid
		}
	}
	brand := models.Query(`select id,name from mt_brand where cid like '%` + cid + `,%' order by sort desc`)
	w = append(w, `a.status=1`)
	w = append(w, `a.censoring=1`)
	cidss := strings.Join(cids, ",")
	w = append(w, `a.cid in(`+cidss+`)`)
	bid := c.GetString("bid")
	if bid != "" {
		w = append(w, `a.bid=`+bid)
	}
	min := c.GetString("min")
	if min != "" {
		w = append(w, `a.price>=`+min)
	}
	max := c.GetString("max")
	if max != "" {
		w = append(w, `a.price<=`+max)
	}
	ws := strings.Join(w, ` and `)
	status := c.GetString("status")
	var ob string
	switch status {
	case "":
		ob = ` order by a.recommend desc,a.sort desc`
	case "0":
		ob = ` order by a.price desc`
	case "1": //价格
		ob = ` order by a.price`
	case "2": //价格
		ob = ` order by a.sellnum desc`
	}
	page, _, num := models.Pagechange(c.GetString("page"), "")
	lt := ` limit ` + page + `,` + num
	sql := `select a.title,a.keywords,a.price,a.gid,a.id,a.isvip,a.sellnum,a.issellnum,b.pathname,c.name as gname,d.name as shen from mt_product a left join mt_resources b on a.img=b.id left join mt_shop c on a.gid=c.id 
	left join mt_area d on c.province=d.id where ` + ws + ob + lt
	info := mobile.ProductList(sql, c.Uid)
	if c.IsAjax() {
		var js = make(map[string]interface{})
		js["info"] = info
		js["brand"] = brand
		js["attribute_column"] = attribute_column
		c.Data["json"] = js
		c.ServeJSON()
	} else {
		c.Data["info"] = info
		c.Data["brand"] = brand
		c.Data["title"] = column["name"]
		c.Data["s_title"] = column["name"]
		c.Data["s_url"] = models.Urlc + c.Ctx.Request.RequestURI
		c.Data["s_img"] = column["pathname"]
		c.Data["attribute_column"] = attribute_column
		c.Data["status"] = status
		c.Data["min"] = min
		c.Data["max"] = max
		c.Data["bid"] = bid
		c.Data["urls"] = urls + `min=` + min + `&max=` + max + `&bid=` + bid + `&id=` + cid
		c.Data["urlss"] = `/mobile/column/list?id=` + cid + `&status=` + status + `&`
		// c.Data["urlajax"] = `/mobile/column/search_result?keywords=` + keywords + `&status=` + status
		c.TplName = "wechat/column/list.html"
	}
}

type ColumnProductEvaluate struct {
	BaseController
}

func (c *ColumnProductEvaluate) Get() {
	id := c.GetString("id")
	var w []string
	w = append(w, `a.status=1`)
	w = append(w, `a.censoring=1`)
	w = append(w, `a.sid=0`)
	ws := strings.Join(w, ` and `)
	ob := ` order by a.addtime desc `
	page, _, num := models.Pagechange(c.GetString("page"), "")
	lt := ` limit ` + page + `,` + num
	sql := `select a.id,a.score,a.img,a.addtime,a.content,c.pathname,b.monicker from mt_product_evaluation a left join mt_member b 
				on a.uid=b.id left join mt_resources c on b.avatar=c.id join (select * from mt_order_car where pid=` + id + `) d on 
				a.cid=d.id where ` + ws + ob + lt
	info := models.Query(sql)
	for _, v := range info {
		monicker := fmt.Sprint(v["monicker"])
		monickers := strings.Split(monicker, "")
		v["monicker"] = monickers[0] + `****` + monickers[len(monickers)-1]
		if img := fmt.Sprint(v["img"]); img != "" && img != "<nil>" {
			v["imgs"] = models.Query(`select pathname from mt_resources where id in(` + img + `)`)
		}
	}
	all := models.Query(`select count(a.id) as num from mt_product_evaluation a join (select * from mt_order_car where pid=` + id + `) d on 
				a.cid=d.id where ` + ws)[0]["num"]
	good := models.Query(`select count(a.id) as num from mt_product_evaluation a join (select * from mt_order_car where pid=` + id + `) d on 
				a.cid=d.id where a.score>3 and ` + ws)[0]["num"]
	middle := models.Query(`select count(a.id) as num from mt_product_evaluation a join (select * from mt_order_car where pid=` + id + `) d on 
				a.cid=d.id where a.score=3 and ` + ws)[0]["num"]
	nogood := models.Query(`select count(a.id) as num from mt_product_evaluation a join (select * from mt_order_car where pid=` + id + `) d on 
				a.cid=d.id where a.score<3 and ` + ws)[0]["num"]
	pic := models.Query(`select count(a.id) as num from mt_product_evaluation a join (select * from mt_order_car where pid=` + id + `) d on 
				a.cid=d.id where a.img<>'' and ` + ws)[0]["num"]
	product := models.Query(`select a.title,a.description,b.pathname from mt_product a left join mt_resources b on a.img=b.id`)[0]
	if c.IsAjax() {
		var js = make(map[string]interface{})
		js["info"] = info
		js["all"] = all
		js["good"] = good
		js["middle"] = middle
		js["nogood"] = nogood
		js["pic"] = pic
		js["product"] = product
		c.Data["json"] = js
		c.ServeJSON()
	} else {
		c.Data["info"] = info
		c.Data["all"] = all
		c.Data["good"] = good
		c.Data["middle"] = middle
		c.Data["nogood"] = nogood
		c.Data["pic"] = pic
		c.Data["s_title"] = product["title"].(string) + `的评价`
		c.Data["s_desc"] = product["description"]
		c.Data["s_url"] = models.Urlc + c.Ctx.Request.RequestURI
		c.TplName = "wechat/column/product_evaluate.html"
	}
}

type ContactService struct {
	BaseController
}

func (c *ContactService) Get() {
	gid := c.GetString("id")
	if gid == "0" {
		if c.Uid != "" {
			sid := fmt.Sprint(models.Query(`select sid from mt_member where id=` + c.Uid)[0]["sid"])
			var sids []string
			if sid == "" || sid == "<nil>" || sid == "0" {
				service := models.Query(`select id from mt_member where service=1`)
				for _, v := range service {
					sids = append(sids, v["id"].(string))
				}
			}
			for _, v := range sids {
				if is := models.Query(`select id from mt_sms where (uid=` + c.Uid + ` and fid=` + v + `) or (fid=` + c.Uid + ` and uid=` + v + `)`); is != nil {
					sid = v
					models.Exec(`update mt_member set sid=` + sid + ` where id=` + c.Uid)
					break
				}
			}
			if sid == "" || sid == "<nil>" || sid == "0" {
				r := rand.New(rand.NewSource(time.Now().UnixNano()))
				sid = sids[r.Intn(len(sids))]
			}
			if sid == "" || sid == "<nil>" || sid == "0" {
				sid = fmt.Sprint(models.Systems()["uid"])
			}
			if c.IsAjax() {
				c.Data["json"] = sid
				c.ServeJSON()
			} else {
				c.Ctx.Redirect(302, "/mobile/my/message_content?id="+sid)
			}
		} else {
			c.Ctx.Redirect(302, "/mobile/login")
		}
	} else {
		var uids []string
		service := models.Query(`select id from mt_member where gid=` + gid + ` and service=1`)
		for _, v := range service {
			uids = append(uids, v["id"].(string))
		}
		var uid string
		for _, v := range uids {
			if is := models.Query(`select id from mt_sms where (uid=` + c.Uid + ` and fid=` + v + `) or (fid=` + c.Uid + ` and uid=` + v + `)`); is != nil {
				uid = v
				break
			}
		}
		if uid == "" {
			if len(uids) > 0 {
				r := rand.New(rand.NewSource(time.Now().UnixNano()))
				uid = uids[r.Intn(len(uids))]
			}
		}
		if uid == "" {
			uid = models.Query(`select uid from mt_shop where id=` + gid)[0]["uid"].(string)
		}
		if c.IsAjax() {
			c.Data["json"] = uid
			c.ServeJSON()
		} else {
			c.Ctx.Redirect(302, "/mobile/my/message_content?id="+uid)
		}
	}
}
